package com.example.app1

import android.content.Context
import android.graphics.Canvas
import android.graphics.DashPathEffect
import android.graphics.Paint
import android.graphics.Path
import android.graphics.PathDashPathEffect
import android.graphics.PathMeasure
import android.util.AttributeSet
import android.view.View

class DashBoard(context: Context?, attrs: AttributeSet?) : View(context, attrs) {

    private val dashLength = 10.dp
    private val dashWidth = 3.dp
    private val arcRadius = 100.dp
    private val openAngle = 120f
    private val dashCount = 10

    private val path = Path()
    private val dashPath = Path()
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private lateinit var dashEffect: PathDashPathEffect

    init {
        paint.style = Paint.Style.STROKE
        paint.strokeWidth = 2.dp
        paint.strokeCap = Paint.Cap.ROUND

        dashPath.addRect(0f, 0f, dashWidth, dashLength, Path.Direction.CCW)
    }
    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        path.addArc(
            width / 2f - arcRadius,
            height / 2f - arcRadius,
            width / 2f + arcRadius,
            height / 2f + arcRadius,
            90 + openAngle / 2,
            360 - openAngle
        )
        // 需要知道刻度之间留多少距离
        val pathMeasure: PathMeasure = PathMeasure()
        pathMeasure.setPath(path, false)
        val length = pathMeasure.length
        // 刻度的宽度是包含在advance里面的
        dashEffect = PathDashPathEffect(dashPath, (length - dashWidth) / (dashCount - 1), 0f, PathDashPathEffect.Style.ROTATE)

    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        // 画一个对应的刻度
        paint.pathEffect = dashEffect
        canvas.drawPath(path, paint)
        // 画一个大半圆弧
        paint.pathEffect = null
        canvas.drawPath(path, paint)

    }
}